<template>
  <!--  出库任务-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="批次号">
          <el-input v-model="searchParam.batchNo" placeholder="请输入批次号" clearable style="width: 200px"/>
        </el-form-item>
        <el-form-item label="物料">
          <el-select v-model="searchParam.materialId" placeholder="请选择物料" clearable filterable remote
                     :remote-method="remoteMateriaList"
                     style="width: 201px">
            <el-option v-for="item in materiaList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
          <!--          <el-input v-model="searchParam.materialId" placeholder="请选择物料" clearable style="width: 200px"/>-->
        </el-form-item>
        <el-form-item label="出库仓库">
          <el-tree-select v-model="searchParam.wareId" :data="wareList" check-strictly clearable filterable
                          :render-after-expand="false" :props="{
							children: 'storageBaseStateVOList',
							label: 'name',
							value: 'id',
						}" style="width: 201px" @change="wareChange"/>
        </el-form-item>
        <el-form-item label="出库库位">
          <el-select v-model="searchParam.targetStorageId" placeholder="请选择出库库位" clearable filterable multiple
                     max-collapse-tags="1" collapse-tags collapse-tags-tooltip
                     style="width: 201px">
            <el-option v-for="item in storageList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="业务类型" prop="transferType">
          <el-select v-model="searchParam.transferType" filterable placeholder="请选择业务类型" style="width: 201px">
            <el-option v-for="item in businessTypeList" :key="item.value" :label="item.label"
                       :value="item.value"/>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          <el-button class="refreshBtn" :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">
          <div>列表信息</div>
        </div>
        <div class="pageTableButView">
          <!--          <el-button  type="primary" @click="handleAdd" :icon="Plus">新建</el-button>-->
        </div>
      </div>
      <!-- 表格 -->
      <el-table :data="paginatedData" height="calc(100vh - 400px)" row-key="id" :stripe="false" border
                header-cell-class-name="witheTableHeader">
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope"> {{ (currentPage - 1) * pageSize + scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="单据号" prop="taskNo" min-width="150" show-overflow-tooltip align="center"/>
        <!--        <el-table-column label="单据号" prop="orderNo" min-width="150" show-overflow-tooltip align="center"/>-->
        <el-table-column label="物料" prop="materialName" min-width="210" show-overflow-tooltip align="center"/>
        <el-table-column label="批次号" prop="batchNo" min-width="210" show-overflow-tooltip align="center"/>
        <!--        <el-table-column label="生产计划号" prop="planNo" min-width="210" show-overflow-tooltip align="center"/>-->
        <!--        <el-table-column label="追溯码" prop="traceCode" min-width="250" show-overflow-tooltip align="center"/>-->
        <el-table-column label="需求数量" prop="count" min-width="100" show-overflow-tooltip align="center"/>
        <el-table-column label="实际出库数量" prop="outboundCount" min-width="120" show-overflow-tooltip align="center"/>
        <el-table-column label="出库库位" prop="outboundPosition" min-width="150" show-overflow-tooltip align="center"/>
        <el-table-column label="业务类型" prop="outboundOrderType" :formatter="transferTypeFormatter" min-width="100"
                         show-overflow-tooltip align="center"/>
        <el-table-column label="单据状态" prop="status" :formatter="inboundStatusListFormatter" min-width="100"
                         show-overflow-tooltip align="center"/>
        <!--				<el-table-column label="businessType" prop="businessType" min-width="100"	show-overflow-tooltip align="center" />-->
        <!--        <el-table-column prop="remark" align="center" min-width="200" label="退库备注" show-overflow-tooltip/>-->
        <el-table-column label="创建时间" prop="createTime" min-width="200" show-overflow-tooltip align="center"/>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" :icon="Tickets" @click="handleEdit(scope.row, 1)">驳回</el-button>
            <el-button type="text" size="small" :icon="DocumentChecked" @click="doFinish(scope.row)">出库确认</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background layout="sizes, prev,pager, next,total" :total="pageTotal" :page-size="pageSize"
                       :current-page="currentPage" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </div>
    <!-- 编辑/新建弹框 -->
    <el-dialog v-model="showCrud" :title="crudTitle + '出库单'" width="1000px">
      <el-form :model="formData" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="工序订单" prop="procedureOrderId">
              <el-select v-model="formData.procedureOrderId" placeholder="请选择工序订单" clearable filterable
                         style="width: 201px" :disabled="popType == 1">
                <el-option v-for="item in procedureOrderList" :key="item.id" :label="item.no" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出库仓库">
              <el-tree-select v-model="formData.wareId" :data="wareList" :disabled="popType == 1" check-strictly
                              :render-after-expand="false" :props="{
									children: 'sonList',
									label: 'warehouseName',
									value: 'id',
								}" style="width: 201px" @change="wareChange"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出库库位" prop="targetStorageId">
              <el-select v-model="formData.targetStorageId" :disabled="popType == 1" placeholder="请选择"
                         style="width: 201px">
                <el-option v-for="item in storageList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <div class="pageTableTitle">物料列表</div>
        </el-row>
        <el-row :gutter="10" style="padding: 10px">
          <el-table :data="formData.details" style="width:100% " height="300px">
            <el-table-column label="序号" type="index" align="center" width="80"/>
            <el-table-column prop="materialId" label="物料编码" align="center">
              <template #default="scope">
                <el-select v-model="scope.row.materialId" :disabled="popType == 1" placeholder="" clearable filterable>
                  <el-option v-for="item in materiaList" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="materialCount" label="数量" align="center" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.materialCount" type="number" :disabled="popType == 1"
                          placeholder=""></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="batchNo" label="批次号" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.batchNo" placeholder="" :disabled="popType == 1"
                          style="width: 100%"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" width="110" fixed="right" v-if="popType != 1">
              <template #header>
                <el-button :icon="Plus" @click="handleAddConfigLine">新建</el-button>
              </template>
              <template #default="scope">
                <!--                <el-button @click="handleEditConfigLine(scope.row,scope.$index)"-->
                <!--                           plain :icon="Edit">-->
                <!--                  编辑-->
                <!--                </el-button>-->
                <el-button type="danger" plain :icon="Delete" @click="handleConfigDelete(scope.$index)"> 删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="showCrud = false">取消</el-button>
					<el-button type="primary" @click="handleSave">保存</el-button>
				</span>
      </template>
    </el-dialog>
    <!-- 查看详情弹框 -->
    <el-dialog v-model="showDetail" :title="crudTitle + '出库单'" width="1000px">
      <el-form :model="formData" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="工序订单："> {{ formData.procedureOrderName || '--' }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出库仓库："> {{ formData.targetWarehouseName || '--' }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出库库位："> {{ formData.targetStorageName || '--' }}</el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <div class="pageTableTitle">物料列表</div>
        </el-row>
        <el-row :gutter="10" style="padding: 10px">
          <el-table :data="formData.details" style="width:100% " height="300px">
            <el-table-column label="序号" type="index" align="center" width="80"/>
            <el-table-column prop="materialName" label="物料名称" align="center"/>
            <el-table-column prop="materialCount" label="数量" align="center" width="150"/>
            <el-table-column prop="batchNo" label="批次号" align="center"/>
            <el-table-column align="center" width="110" fixed="right" v-if="popType != 1">
              <template #header>
                <el-button :icon="Plus" @click="handleAddConfigLine">新建</el-button>
              </template>
              <template #default="scope">
                <el-button type="danger" plain :icon="Delete" @click="handleConfigDelete(scope.$index)"> 删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="showDetail = false">关闭</el-button>
				</span>
      </template>
    </el-dialog>
    <!-- 点击出库弹窗 -->
    <el-dialog v-model="showOutIn" title="出库" width="1000px">
      <el-form :model="outInForm" :rules="outInRules" ref="outInFormRef" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="物料名称"> {{ outInForm.materialName || '--' }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次号"> {{ outInForm.batchNo || '--' }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数量" prop="materialCount" required>
              <el-input v-model="outInForm.materialCount" type="number" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出库仓库">
              <el-tree-select v-model="outInForm.targetWarehouseId" :data="wareList" check-strictly
                              :render-after-expand="false" :props="{
									children: 'sonList',
									label: 'warehouseName',
									value: 'id',
								}" @change="wareChange"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出库库位" prop="targetStorageId" required>
              <el-select v-model="outInForm.targetStorageId" placeholder="请选择">
                <!--                sourceStorageId-->
                <el-option v-for="item in storageList" :key="item.id" :label="item.storageName" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="二维码" prop="batchNo" required>
              <el-input v-model="outInForm.batchNo" placeholder=""></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="showOutIn = false">取消</el-button>
					<el-button type="primary" @click="outInSum(outInFormRef)">保存</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {ref, computed, watch, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {
  Delete, Edit, Tickets, DocumentChecked
  , Search, Share, Upload, Refresh, Plus, DocumentCopy, Files
} from '@element-plus/icons-vue';
import type {FormInstance, FormRules} from 'element-plus';
import {inject} from 'vue'

const inboundStatusList = inject('inboundStatusList')
const paginatedData = ref([]);
const pageSize = ref(10);
const currentPage = ref(1);
const searchParam = ref({});
const handleSizeChange = (val) => {
  pageSize.value = val;
  getList();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getList();
};


const formData = ref({
  planNo: '',
  name: '',
  planBeginTime: null,
  planEndTime: null,
  actualBeginTime: null,
  actualEndTime: null,
  organizationId: '',
  status: '0',
  type: '0'
});

const crudTitle = computed(() => {
  if (popType.value === 1) {
    return '查看';
  } else {
    return isEdit.value ? '编辑' : '新建';
  }
});

const showDetail = ref(false);


// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  currentPage.value = 1;
  // currentPage.value = 1
  getList();
};

const procedureOrderList = ref([]);
const wareList = ref([]);
const storageList = ref([]);
const materiaList = ref([]);
const showOutIn = ref(false);
const outInForm = ref({
  materialName: '',
  materialCount: '',
  wareId: '',
  targetStorageId: '',
  batchNo: ''
});
const outInFormRef = ref(null);
const outInRules = reactive<FormRules<outInForm>>({
  materialCount: [
    {required: true, message: '请输入数量', trigger: 'blur'}
  ],
  wareId: [
    {required: true, message: '请选择出库仓库', trigger: 'change'}
  ],
  targetStorageId: [
    {required: true, message: '请选择出库库位', trigger: 'change'}
  ],
  batchNo: [
    {required: true, message: '请选择批次号', trigger: 'blur'}
  ]
});
const handleAddConfigLine = () => {
  formData.value.details.push({
    materialId: null,
    materialCount: null,
    batchNo: null
  });
};
const outInSum = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid, fields) => {
    if (valid) {
      const param = outInForm.value;
      outFatherInfo.value.details = [param];
      outFatherInfo.value.tasks = [param];
      axiosInstance.post('/api/warehouseMaterialTransferOrder/inStock', outFatherInfo.value)
          .then((res) => {
            if (res.code !== 200) {
              ElMessage.warning(res.message);
              return false;
            }
            showOutIn.value = false;
            getList();
          });
    }
  });

};

const outFatherInfo = ref({});

const doOutIn = (row) => {
  const param = JSON.parse(JSON.stringify(row));
  outInForm.value = param;
  // this.materialCount = JSON.parse(JSON.stringify(param.materialCount))
  // 循环列表 找出子单据的父级
  // 提交时只提交父级和该条子单据

  for (const item of paginatedData.value) {
    if (item.children && item.children.length > 0) {
      for (const items of item.children) {
        if (items.id === row.id) {
          outFatherInfo.value = item;
          outInForm.value.targetWarehouseId = item.targetWarehouseId;
          outInForm.value.targetStorageId = item.targetStorageId;
          wareChange(item.targetWarehouseId);
        }
      }
    }
  }
  showOutIn.value = true;
};

const handleConfigDelete = (e) => {
  formData.value.details.splice(e, 1);
};


const wareChange = (e) => {
  axiosInstance.get('/api/logistics/storagePosition/getStoragePositionWithBaseId', {
    params: {
      storageBaseId: e
    }
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        searchParam.value.targetStorageId = null
        storageList.value = res.data;
      });
};

const getOption = () => {
  axiosInstance
      .post('/api/basedata/material/getPage', {}).then(res => {
    if (res.code == 200) {
      materiaList.value = res.data.records;
    }
  });
  // axiosInstance.post('/api/planProcedureOrder/getAll', {})
  //     .then(res => {
  //       if (res.code !== 200) {
  //         ElMessage.error(res.message);
  //         return false;
  //       }
  //       const list = res.data;
  //       const loop = [];
  //       for (const item of list) {
  //         loop.push(
  //             {
  //               value: item.id,
  //               label: item.materialName
  //             }
  //         );
  //       }
  //       procedureOrderList.value = list;
  //     });

  axiosInstance.get('/api/logistics/storageBase/queryStorageBaseTree', {}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    wareList.value = res.data;
  });
};


const getTypeName = (type: string) => {
  const name = typeList.value.find((item: any) => item.value === type);
  return name ? name.label : '';
};

const typeList = ref([
  {label: '未完成', value: '0'},
  {label: '已完成', value: '1'}
]);

const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框

const transferType = ref({status: 'PENDING_APPROVAL'});

// 新建记录
const handleAdd = () => {
  popType.value = 0;
  isEdit.value = false;
  formData.value = {
    details: [{
      materialId: null,
      materialCount: null,
      batchNo: null
    }]
  };
  showCrud.value = true;
};


const businessTypeList = inject('businessOutTypeList')

const transferTypeFormatter = (row) => {
  const found = businessTypeList.find(
      item => item.value == row.outboundType
  );
  return found ? found.label : '未知类型'; // 明确处理未找到的情况
};

const inboundStatusListFormatter = (row, column, cellValue) => {
  const foundItem = inboundStatusList.find(item => cellValue == item.value);
  return foundItem ? foundItem.label : '';
};

const popType = ref(0);//0 编辑 1 只读


const doFinish = (row) => {
  ElMessageBox.confirm('是否出库确认?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'success'
  })
      .then(() => {
        const param = {
          count: row.count,
          taskId: row.id
        };
        axiosInstance.post('/api/logistics/materialDetail/outStock', param)
            .then(res => {
              if (res.code !== 200) {
                ElMessage.error(res.message);
                return false;
              }
              ElMessage.success('确认成功');
              getList();
            });
      });
};

const formatStatus = (row, column, cellValue) => {
  switch (cellValue) {
    case 'transfer':
      return '调拔';
    case 'instock':
      return '出库';
    case 'outstock':
      return '出库';
    case 'pick':
      return '备料';
  }
};

const rejectShow = ref({});

const remoteMateriaList = (e) => {
  if (!e) {
    return false
  }
  const param = {
    current: 1, pageSize: 30, name: e
  };
  // if (searchMaterialProperData.value) {
  //   param.materialProperties = '0';
  // } else {
  //   delete param.materialProperties;
  // }
  axiosInstance.post('/api/basedata/material/getPage', param).then(res => {
    materiaList.value = res.data.records;
  });
};


// 编辑记录
const
    handleEdit = (row: any, type) => {
      // console.log(row,'czqRow')
      ElMessageBox.prompt('请输入驳回原因', '驳回', {
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      })
          .then(({value}) => {
            const param = {...row}
            param.description = value;
            axiosInstance.post('/api/logistics/outboundItem/reject', param).then((res) => {
              if (res.code === 200) {
                getList();
                ElMessage.success('驳回成功');

              } else {
                ElMessage.warning(res.message);
              }
            });
          });
      // isEdit.value = true;
      // formData.value = {...row};
      // axiosInstance.post('/api/warehouseMaterialTransferOrder/getDetailById', {id: row.id}).then(res => {
      //   if (res.code !== 200) {
      //     ElMessage.warning(res.message);
      //     return false;
      //   }
      //   formData.value.details = res.data.children
      //   if (type) {
      //     // 查看详情
      //     popType.value = type
      //     showDetail.value = true
      //   } else {
      //     // 编辑
      //     popType.value = 0
      //     showCrud.value = true;
      //   }
      //   wareChange(e.targetWarehouseId)
      // })
    };


// 保存记录
const handleSave = async () => {
  const param = formData.value;
  if (param.details.length == 0) {
    ElMessage.warning('请选择物料');
    return false;
  }
  for (const item of param.details) {
    if (!item.materialId) {
      ElMessage.warning('请选择物料');
      return false;
    }
    if (!item.materialCount || item.materialCount === 0) {
      ElMessage.warning('请输入数量');
      return false;
    }


  }
  axiosInstance.post('/api/warehouseMaterialTransferOrder/save', {...param, ...transferType.value})
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        showCrud.value = false;
        getList();
      });
};

// 展开行处理
const expandedRowKeys = ref<string[]>([]);
const handleExpandChange = (row: any, expandedRows: any[]) => {
  if (expandedRows.includes(row)) {
    rowChildren(row);
  } else {
    // getList();
  }
};

const rowChildren = (row: any) => {
  axiosInstance.post('/api/warehouseMaterialTransferOrder/getDetailById', {id: row.id}).then(res => {
    if (res.code !== 200) {
      ElMessage.warning(res.message);
      return false;
    }
    const listGroup = paginatedData.value.map((item) => {
      if (item.id === row.id) {
        return {...item, children: res.data.children};
      }
      return item;
    });
    paginatedData.value = listGroup;
  });
  // axiosInstance.post('/api/basedataQualityScheme/getAll', {planId: row.id})
  //     .then(res => {
  //       if (res.code !== 200) {
  //         ElMessage.error(res.message);
  //         return false
  //       }
  //
  //       .value = res.data
  //     });

  // ProductionPlanDetailApi().then((res) => {
  //   if (res.code !== 200) {
  //     ElMessage.warning(res.message);
  //     return false;
  //   }
  //   const listGroup = paginatedData.value.map((item) => {
  //     if (item.id === row.id) {
  //       return {...item, children: res.data.records};
  //     }
  //     return item;
  //   });
  //   paginatedData.value = listGroup;
  // });
};

const pageTotal = ref(0);

// 获取列表
const getList = async () => {
  axiosInstance.post('/api/logistics/outboundItem/getPage', {
    ...searchParam.value,
    current: currentPage.value,
    pageSize: pageSize.value,
    ...transferType.value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records.map((item) => ({
          ...item,
          children: [],
          layer: 1,
          _loading: false
        }));
        pageTotal.value = res.data.total;
      });
};

onMounted(() => {
  getList();
  getOption();
});
</script>
<style scoped lang="scss"></style>
